﻿using App;
using Grpc.Core;

namespace GrpcDemo.Server.Services
{
    public class CaculatorService : Calculator.CalculatorBase
    {
        private readonly ILogger<CaculatorService> _logger;

        public CaculatorService(ILogger<CaculatorService> logger)
        {
            _logger = logger;
        }

        public override Task<OutputMessage> Add(InputMessage request, ServerCallContext context)
            => InvokeAsync((x, y) => x + y, request);

        public override Task<OutputMessage> Div(InputMessage request, ServerCallContext context)
        => InvokeAsync((x, y) => x / y, request);

        public override Task<OutputMessage> Mul(InputMessage request, ServerCallContext context)
        => InvokeAsync((x, y) => x * y, request);

        public override Task<OutputMessage> Sub(InputMessage request, ServerCallContext context)
        => InvokeAsync((x, y) => x - y, request);

        private Task<OutputMessage> InvokeAsync(Func<int, int, int> calculate, InputMessage input)
        {
            OutputMessage output;

            try
            {
                output = new OutputMessage
                {
                    Status = 0,
                    Result = calculate.Invoke(input.X, input.Y)
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "calculte error.");
                output = new OutputMessage { Error = ex.Message, Status = 1 };
            }

            return Task.FromResult(output);
        }
    }
}
